/**
 * 
 */
package freedom.needle.types;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.StringType;
import org.hibernate.usertype.UserType;

/**
 * @author charlie
 *
 */
public abstract class NameEnumType<E extends Enum<E>> implements UserType {

	private static final int[] SQL_TYPES = { Types.VARCHAR };

	@Override
	public abstract Class<E> returnedClass();

	@Override
	public int[] sqlTypes() {
		return SQL_TYPES;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y)
			return true;
		if (null == x || null == y)
			return false;
		return x.equals(y);
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
			throws HibernateException, SQLException {
		String name = (String) StringType.INSTANCE.nullSafeGet(rs, names[0], session, owner);
		E object = null;
		if (!rs.wasNull() && null != name) {
			object = Enum.valueOf(returnedClass(), name);
		}
		return object;
	}

	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
			throws HibernateException, SQLException {
		if (null == value) {
			st.setNull(index, Types.VARCHAR);
		} else {
			StringType.INSTANCE.nullSafeSet(st, ((Enum<?>) value).name(), index, session);
		}

	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public boolean isMutable() {
		return false;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	@Override
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	@Override
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}

}
